package com.leaf.lowcode.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.leaf.lowcode.API.PeronQueryApi;
import com.leaf.lowcode.API.VistorEventApi;
import com.leaf.lowcode.entity.*;
import com.leaf.lowcode.mapper.ApptionmentMapper;
import com.leaf.lowcode.mapper.HkVisitorMapper;
import com.leaf.lowcode.utils.RegularInstance;
import com.leaf.lowcode.utils.jsontobean.JsonToBeanV;
import com.tencent.welink.iot.SubDeviceDTO;
import com.tencent.welink.iot.WelinkHttp;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class VistorEvent {
    @Autowired
    private HkVisitorMapper hkVisitorMapper;

    @Autowired
    private ApptionmentMapper apptionmentMapper;


  //  @Scheduled(initialDelay =  1000, fixedRate = 6*1000)
    void  execute()
    {
        List<SubDeviceDTO> subDeviceDTOList = RegularInstance.subDeviceDTOList;
        System.out.println("sub"+subDeviceDTOList);
        Calendar calendar = new GregorianCalendar();
        calendar.add(Calendar.DAY_OF_MONTH,0);
        //一天的开始时间 yyyy:MM:dd 00:00:00
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        Date dayStart = calendar.getTime();
        String pattern = "YYYY-MM-dd'T'HH:mm:ssZZ";
        String startStr = DateFormatUtils.format(dayStart,pattern);
        System.out.println("startStr"+startStr);
        //一天的结束时间 yyyy:MM:dd 00:00:00
        calendar.set(Calendar.HOUR_OF_DAY,23);
        calendar.set(Calendar.MINUTE,59);
        calendar.set(Calendar.SECOND,59);
        calendar.set(Calendar.MILLISECOND,999);
        Date dayEnd = calendar.getTime();
        String endStr=DateFormatUtils.format(dayEnd,pattern);
        System.out.println("startStr"+endStr);

      //   String  orgName;
      System.out.println("访客事件启动");
      VistorEventApi vistorEventApi =new VistorEventApi();
      RecordsRequest   searchesRequest= new RecordsRequest();
        searchesRequest.setPageNo(1);
        searchesRequest.setPageSize(1000);
       // searchesRequest.setVisitEndTimeBegin(startStr);
       // searchesRequest.setVisitEndTimeEnd(endStr);
        String StringtoJson=vistorEventApi.eventSearch(searchesRequest);
        JSONObject  vistorJson= JSON.parseObject(StringtoJson);
        System.out.println(vistorJson);
        JSONArray vistorList= (JSONArray) ((JSONObject)vistorJson.get("data")).get("list");
        HkVistor hkVistor=new HkVistor();
        HkVistor flag;

        /**
         * 查询访客来访记录
         */
        for(int i=0;i<vistorList.size();i++)
        {
              JSONObject  vistorToJson = (JSONObject) vistorList.get(i);
              JsonToBeanV<HkVistor> jsontoBean=new JsonToBeanV<>();
              hkVistor=jsontoBean.tansfrom(hkVistor,vistorToJson);
              flag=hkVisitorMapper.selectId(hkVistor.getOrderId());
              if(flag==null)
              {
               System.out.println("不存在");
               hkVisitorMapper.insert(hkVistor);
              }
        }

        /**
         *今日访客预约
         */
        ApptionmentBean apptionmentBean=new ApptionmentBean();
        ApptionmentBean flag1;
        String json=vistorEventApi.appointmentSearch(searchesRequest);
        JSONObject apptionmentjson=JSON.parseObject(json);
        JSONArray apption = (JSONArray) ((JSONObject) apptionmentjson.get("data")).get("list");
        JsonToBeanV<ApptionmentBean>  jsonToBeanV=new JsonToBeanV<ApptionmentBean>();
        for(int i=0;i<apption.size();i++) {
          JSONObject jsonbean  = (JSONObject) apption.get(i);
          apptionmentBean.setVisitorStatus((Integer) jsonbean.get("visitorStatus"));
          apptionmentBean.setReceptionistCode((String) jsonbean.get("receptionistCode"));
            apptionmentBean=jsonToBeanV.tansfrom(apptionmentBean,jsonbean);
            flag1 =apptionmentMapper.selectId(apptionmentBean.getOrderId());
               if(flag1==null)
               {
                   System.out.println("访客预约不存在");
                   apptionmentMapper.insert(apptionmentBean);
                   PeronQueryApi peronQueryApi= new PeronQueryApi();
                   ArrayList<String> list =new ArrayList();
                   PersonInfoRequest personInfoRequest=new PersonInfoRequest();
                   personInfoRequest.setParamName("personId");
                   list.add(apptionmentBean.getReceptionistId());
                   personInfoRequest.setParamValue(list);
                   String personinfo=peronQueryApi.personInfoSearch(personInfoRequest);
                   JSONObject personJson= (JSONObject) JSON.parse(personinfo);
                   JSONArray json1 = (JSONArray) ((JSONObject)personJson.get("data")).get("list");
                   String  orgName = null;
                   for(int j=0;j<json1.size();j++)
                   {
                       orgName  = (String) ((JSONObject) json1.get(j)).get("orgName");
                   }


                   System.out.println("准备进入门禁系统");
                               //  System.out.println("======================门禁卡========================"+readerdoorstatesend.getIndexCode());
                               JSONObject standardData = new JSONObject();
                               standardData.put("reportTs", System.currentTimeMillis());
                               JSONObject profile = new JSONObject();
                               profile.put("modelId", 200699);
                               profile.put("poiCode", "w0717006");
                               standardData.put("profile", profile);
                               WelinkHttp wh = new WelinkHttp(RegularInstance.registerData1, RegularInstance.loginData);
                               JSONObject events = new JSONObject();
                               JSONObject event = new JSONObject();
                               JSONObject dayls=new JSONObject();
                               JSONObject dayrates=new JSONObject();
                               JSONObject properties = new JSONObject();
                               JSONObject propertie = new JSONObject();

                               List<String> daylist=apptionmentMapper.sumElectricityProduction();
                               List<String> daylist2=hkVisitorMapper.sumElectricityProduction();
                         //todo i1 <daylist.size()

                                   for (int i1 = 0, j = 1; i1 <2; i1++, j++) {
                                       double sumday = Double.parseDouble(daylist.get(i1));
                                       String day = "day" + j + "";
                                       dayls.put(day, sumday);
                                       double visrtsumday=Double.parseDouble(daylist2.get(i1));
                                       double rate=visrtsumday/sumday;
                                       dayrates.put(day,rate);
                                   }


                   propertie.put("daylist",daylist);
                   propertie.put("sumrate",dayrates);
                   propertie.put("eventType", 1);
                   propertie.put("eventTs", System.currentTimeMillis());
                   propertie.put("describe", "");



                               /**
                                * 访客姓名
                                */
                   propertie.put("visitorName",apptionmentBean.getVisitorName());
                               /**
                                * 证件号码
                                */
                   propertie.put("certificateNo",apptionmentBean.getCertificateNo());

                               /**
                                * 访客车牌号
                                */
                   propertie.put("phoneNo",apptionmentBean.getPhoneNo());

                               /**
                                * 被访人唯一标识
                                */
                   propertie.put("receptionistId",apptionmentBean.getReceptionistId());

                               /**
                                * 被访人姓名
                                */
                   propertie.put("receptionistName",apptionmentBean.getReceptionistName());

                               /**
                                *   开始时间
                                */
                   propertie.put("visitStartTime",apptionmentBean.getVisitStartTime());

                               /**
                                *   结束时间
                                */
                   propertie.put("visitEndTime",apptionmentBean.getVisitEndTime());

                               /**
                                * 被访部门
                                */
                   propertie.put("orgName",orgName);
                               System.out.println("orgName"+orgName);

                               /**
                                * 被访目的
                                */
                   propertie.put("visitPurpose",apptionmentBean.getVisitPurpose());

                               /**
                                *
                                * 访客登记时的登记id,可以用来做访客签离。
                                */
                   propertie.put("orderId",apptionmentBean.getOrderId());

                               /**
                                * 访客联系电话
                                */
                   propertie.put("phoneNo",apptionmentBean.getPhoneNo());
                               /**
                                * 今日访客总数
                                */
                   propertie.put("todyapptionment", vistorList.size());
                               /**
                                * 来访总数
                                */



                   propertie.put("cance","0");

                   propertie.put("visitcount", json1.size());
                   properties.put("doorevencounts",propertie);
                   standardData.put("properties", properties);
                   standardData.put("events", new JSONObject());
                               //standardData.put("properties", "{}");
                               try {
                                   System.out.println("上传数据");
                                   String devRunEvent = JSONObject.toJSONString(standardData, SerializerFeature.WriteMapNullValue);
                                   System.out.println("发送设备运行时事件数据==" + devRunEvent);
                                   System.out.println("--------------------------------开始传输设备运行时事件数据");
                                   wh.sendMessage(RegularInstance.loginData.load(), 80000, Long.parseLong("300000000000209094"), devRunEvent, true);
                                   System.out.println("xxxxx" + devRunEvent + "xxxxx");
                               } catch (Exception e) {
                                   System.out.println("设备运行时事件数据传输出现异常");
                               }
                           }

                       }
                   }
               }
